<template>
  <div class="exhibition-dashboard">
    <!-- 页面头部 -->
    <div class="dashboard-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">《永恒的高迪·圣家堂》管理系统</h1>
          <p class="page-subtitle">VR大空间展览体验 - 预约数据管理</p>
        </div>
        <div class="header-right">
          <div class="admin-info" @click="showAdminInfo">
            <div class="admin-avatar">
              <span class="avatar-text">{{ adminInitials }}</span>
            </div>
            <div class="admin-details">
              <span class="admin-name">{{ adminInfo?.realName || '管理员' }}</span>
              <span class="admin-role">系统管理员</span>
            </div>
          </div>
          <button class="logout-btn" @click="logout">
            <span class="btn-content">
              退出登录
            </span>
          </button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <StatsCards :stats="stats" />

    <!-- 预约数据查询区域 -->
    <div class="booking-section">
      <div class="section-header">
        <h2 class="section-title">预约数据查询</h2>
      </div>

      <!-- 查询条件 -->
      <SearchPanel 
        :searchForm="searchForm"
        @update:searchForm="searchForm = $event"
        @search="searchBookings"
        @reset="resetSearch"
      />

      <!-- 预约数据表格 -->
      <BookingTable 
        :bookings="bookings"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        :table-loading="tableLoading"
        :export-loading="exportLoading"
        @export="exportBookings"
        @view-detail="viewBookingDetail"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 管理员信息弹窗 -->
    <AdminInfoDialog
      :visible="adminInfoDialogVisible"
      @update:visible="adminInfoDialogVisible = $event"
      :edit-visible="editAdminDialogVisible"
      @update:edit-visible="editAdminDialogVisible = $event"
      :admin-info="adminInfo"
      :submit-loading="submitLoading"
      @edit-admin="showEditAdminDialog"
      @submit-edit="submitEditAdmin"
    />

    <!-- 预约详情弹窗 -->
    <BookingDetailDialog
      :visible="bookingDetailDialogVisible"
      @update:visible="bookingDetailDialogVisible = $event"
      :booking-detail="selectedBooking"
    />

  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTokenStore } from '@/stores/token.js'
import { useAdminStore } from '@/stores/admin.js'
import { 
  getAdminInfoService, 
  updateAdminInfoService,
  getBookingListService,
  exportBookingsService,
  getUserStatisticsService
} from '@/api/admin.js'

// 导入组件
import StatsCards from '@/components/StatsCards.vue'
import SearchPanel from '@/components/SearchPanel.vue'
import BookingTable from '@/components/BookingTable.vue'
import AdminInfoDialog from '@/components/AdminInfoDialog.vue'
import BookingDetailDialog from '@/components/BookingDetailDialog.vue'

const router = useRouter()
const tokenStore = useTokenStore()
const adminStore = useAdminStore()

// 管理员信息
const adminInfo = ref(null)
const adminInfoDialogVisible = ref(false)

// 编辑管理员信息弹窗状态
const editAdminDialogVisible = ref(false)

// 提交状态
const submitLoading = ref(false)
const exportLoading = ref(false)
const tableLoading = ref(false)

// 统计数据
const stats = ref({
  totalBookings: 0,
  totalVisitors: 0
})

// 预约数据
const bookings = ref([])
const total = ref(0)
const selectedBooking = ref(null)
const bookingDetailDialogVisible = ref(false)

// 搜索表单
const searchForm = ref({
  searchText: '',
  startDate: '',
  endDate: '',
  periodName: '',
  sortType: 'desc'
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)



// 计算管理员姓名首字母
const adminInitials = computed(() => {
  if (adminInfo.value?.realName) {
    return adminInfo.value.realName.charAt(0).toUpperCase()
  } else if (adminInfo.value?.username) {
    return adminInfo.value.username.charAt(0).toUpperCase()
  }
  return 'A'
})

// 计算属性 - 格式化表格数据中的时间
const formatTableData = (data) => {
  if (!data) return []
  return data.map(item => ({
    ...item,
    createdAt: formatDateTime(item.createdAt),
    bookingDate: formatDate(item.bookingDate)
  }))
}

// 获取管理员信息
const fetchAdminInfo = async () => {
  try {
    const result = await getAdminInfoService()
    if (result.code === 200) {
      adminInfo.value = result.data
      adminStore.setAdminInfo(result.data)
      console.log('管理员信息:', result.data)
    } else {
      console.error('获取管理员信息失败:', result.msg)
    }
  } catch (error) {
    console.error('获取管理员信息异常:', error)
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const userStatsResult = await getUserStatisticsService()
    if (userStatsResult.code === 200) {
      stats.value.totalVisitors = userStatsResult.data.totalUsers || 0
    } else {
      console.error('获取用户统计数据失败:', userStatsResult.msg)
    }
    
    // 预约总数通过查询结果获取
    stats.value.totalBookings = total.value || 0
  } catch (error) {
    console.error('获取统计数据异常:', error)
    stats.value = {
      totalBookings: 0,
      totalVisitors: 0
    }
  }
}

// 获取预约数据列表
const fetchBookings = async () => {
  try {
    tableLoading.value = true
    
    // 构建查询参数
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      searchText: searchForm.value.searchText || '',
      startDate: searchForm.value.startDate || '',
      endDate: searchForm.value.endDate || '',
      periodName: searchForm.value.periodName || '',
      sortType: searchForm.value.sortType || 'desc'
    }
    
    console.log('查询参数:', params)
    
    const result = await getBookingListService(params)
    if (result.code === 200) {
      bookings.value = formatTableData(result.data.items || [])
      total.value = result.data.total || 0
      
      // 更新预约总数统计
      stats.value.totalBookings = result.data.total || 0
    } else {
      console.error('获取预约数据失败:', result.msg)
      ElMessage.error(result.msg || '获取预约数据失败')
      bookings.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取预约数据异常:', error)
    ElMessage.error('获取预约数据失败')
    bookings.value = []
    total.value = 0
  } finally {
    tableLoading.value = false
  }
}

// 搜索预约数据
const searchBookings = async () => {
  console.log('搜索条件:', searchForm.value)
  currentPage.value = 1 // 重置到第一页
  await fetchBookings()
}

// 重置搜索条件
const resetSearch = () => {
  searchForm.value = {
    searchText: '',
    startDate: '',
    endDate: '',
    periodName: '',
    sortType: 'desc'
  }
  currentPage.value = 1
  fetchBookings()
}



// 导出预约数据
const exportBookings = async () => {
  try {
    exportLoading.value = true
    ElMessage.info('正在准备导出文件，请稍候...')
    
    // 构建导出参数
    const exportParams = {
      searchText: searchForm.value.searchText || '',
      startDate: searchForm.value.startDate || '',
      endDate: searchForm.value.endDate || '',
      periodName: searchForm.value.periodName || '',
      sortType: searchForm.value.sortType || 'desc'
    }
    
    console.log('导出参数:', exportParams)
    
    const result = await exportBookingsService(exportParams)
    
    // 创建下载链接
    const blob = new Blob([result], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    const filename = `VR展馆预约列表_${new Date().toISOString().slice(0, 10)}.xlsx`
    link.download = filename
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('预约数据导出成功')
    
  } catch (error) {
    console.error('导出数据异常:', error)
    ElMessage.error(error.message || '导出数据失败，请稍后重试')
  } finally {
    exportLoading.value = false
  }
}

// 查看预约详情
const viewBookingDetail = (booking) => {
  selectedBooking.value = booking
  bookingDetailDialogVisible.value = true
}

// 显示管理员信息
const showAdminInfo = () => {
  adminInfoDialogVisible.value = true
}

// 显示编辑管理员信息弹窗
const showEditAdminDialog = () => {
  adminInfoDialogVisible.value = false
  editAdminDialogVisible.value = true
}

// 提交编辑管理员信息
const submitEditAdmin = async (formData) => {
  try {
    submitLoading.value = true
    
    const result = await updateAdminInfoService(formData)
    
    if (result.code === 200) {
      ElMessage.success('管理员信息修改成功')
      editAdminDialogVisible.value = false
      await fetchAdminInfo()
    } else {
      ElMessage.error(result.msg || '修改失败')
    }
    
  } catch (error) {
    console.error('修改管理员信息异常:', error)
    
    if (error.code && error.msg) {
      ElMessage.error(error.msg)
    } else if (error.response) {
      const message = error.response.data?.msg || error.response.data?.message
      ElMessage.error(message || '修改失败')
    } else {
      ElMessage.error('修改失败，请稍后重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 分页处理
const handleSizeChange = async (val) => {
  pageSize.value = val
  currentPage.value = 1
  await fetchBookings()
}

const handleCurrentChange = async (val) => {
  currentPage.value = val
  await fetchBookings()
}

// 格式化函数（保留少量函数用于Dashboard主页面）
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未知'
  
  try {
    const date = new Date(dateTimeStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return '格式错误'
  }
}

const formatDate = (dateStr) => {
  if (!dateStr) return '未知'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

// 退出登录
const logout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 使用统一的登出方法
    adminStore.logout()
    
    ElMessage.success('退出登录成功')
    router.push('/login')
  } catch {
    // 用户取消
  }
}

onMounted(async () => {
  ElMessage.success('欢迎使用展馆预约管理系统')
  
  // 从store中获取管理员信息
  const storeAdminInfo = adminStore.getAdminInfo()
  if (storeAdminInfo) {
    adminInfo.value = storeAdminInfo
    console.log('从store加载管理员信息:', storeAdminInfo)
  }
  
  // 获取最新的管理员信息
  await fetchAdminInfo()
  
  // 获取预约列表和统计数据
  await fetchBookings()
  await fetchStats()
})
</script>

<style scoped>
.exhibition-dashboard {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 0;
}

/* 页面头部 */
.dashboard-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px 40px;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: bold;
  text-shadow: 0 2px 8px rgba(0,0,0,0.3);
}

.page-subtitle {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
  font-weight: 300;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.admin-info {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.admin-info:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.admin-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 16px;
}

.avatar-text {
  color: white;
}

.admin-details {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.admin-name {
  font-size: 16px;
  font-weight: 600;
  line-height: 1.2;
}

.admin-role {
  font-size: 12px;
  opacity: 0.8;
  line-height: 1.2;
}



/* 预约数据查询区域 */
.booking-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 40px 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}









/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-header {
    padding: 20px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .booking-section {
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 20px;
  }
  
  .admin-info {
    flex-direction: column;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .dashboard-header {
    padding: 15px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .page-subtitle {
    font-size: 14px;
  }
  
  .booking-section {
    padding-left: 15px;
    padding-right: 15px;
  }
}

/* 自定义按钮样式 */
.logout-btn {
  padding: 12px 20px;
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  box-shadow: 0 4px 15px rgba(239, 68, 68, 0.2);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logout-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(239, 68, 68, 0.4);
}

.logout-btn:active {
  transform: translateY(0);
}

.btn-content {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style> 